use std::collections::HashMap;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tokio::fs;
use tokio::sync::Mutex;
use tower_http::follow_redirect::policy::PolicyExt;
use crate::config::{json_IdMd5, json_file};
use crate::models::FileEntry::FileEntry;
use crate::WithAppState::{load_file_Md5, load_file_database};
#[derive(Clone)]
pub struct AppState{
    pub(crate) file_database:Arc<Mutex<Out>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Out{
    pub(crate) data:HashMap<String,FileEntry>,
    pub(crate) id_md5:HashMap<u64,String>,
}
impl AppState{
  pub(crate) async fn new() ->AppState{
         AppState{
         file_database:Arc::new(Mutex::new(Out{
             data:load_file_database(json_file).await,
             id_md5:load_file_Md5(json_IdMd5).await,
         }))
     }
  }
  pub(crate) async fn write_file_data_to_json_idmd5(data:&HashMap<u64,String>){
      let json_content = serde_json::to_string_pretty(&data).expect("序列化 JSON 失败");
      fs::write(json_IdMd5, json_content).await.expect("写入 JSON 文件失败");
  }
    pub(crate) async fn write_file_data_to_json_file(data:&HashMap<String,FileEntry>){
        let json_content = serde_json::to_string_pretty(&data).expect("序列化 JSON 失败");
        fs::write(json_file, json_content).await.expect("写入 JSON 文件失败");
    }
}


